package com.example.myfirstapp;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.widget.TextView;

import com.example.myfirstapp.FeedReaderContract.FeedEntry;

public class DisplayMessageActivity extends ActionBarActivity {

	private FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// !! Has to be call before getting any view in it (eg: TextView...) !!
		setContentView(R.layout.activity_display_message);

		// get the message from the intent
		Intent intent = getIntent();
		String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

		// create the text view
		TextView textView = (TextView) findViewById(R.id.text_view);
		textView.setText(message);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		displayMessageFromDb();

	}

	/**
	 * Displays the message saved in database in the main activity
	 * 
	 * @throws IllegalArgumentException
	 */
	private void displayMessageFromDb() throws IllegalArgumentException {
		// open the database in read mode
		SQLiteDatabase db = mDbHelper.getReadableDatabase();
		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { FeedEntry.COLUMN_NAME_CONTENT };

		Cursor c = db.query(FeedEntry.TABLE_NAME, projection, null, null, null,
				null, null);
		if (!c.moveToFirst()) {
			System.err.println("The cursor is empty");
		}
		String messageFromDb = c.getString(c
				.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_CONTENT));

		TextView textViewDb = (TextView) findViewById(R.id.text_view_db);
		textViewDb.setText(messageFromDb);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
